package cn.chendd.patch.ui.adapters.enums;

import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Properties;

import javax.swing.JOptionPane;
import javax.swing.JTextField;

import cn.chendd.patch.enums.EnumProperties;
import cn.chendd.utils.CloseUtil;
import cn.chendd.utils.LogUtil;
import cn.chendd.utils.PropertiesUtil;

/**
 * 
 * <pre>
 * 保存按钮适配器
 * </pre>
 */
public class SaveParamPropsAdapter extends MouseAdapter {

	private SetPanel setPanel;
	private EnumProperties enumProperties;

	public SaveParamPropsAdapter(SetPanel setPanel , EnumProperties enumProperties) {
		this.setPanel = setPanel;
		this.enumProperties = enumProperties;
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		//取得配置文件
		PropertiesUtil propertiesUtil = new PropertiesUtil(enumProperties);
		Properties configProperties = propertiesUtil.getProperties();

		String configFilePath = propertiesUtil.getPropertiesByPath();
		Component[] c = setPanel.getComponents();
		for (Component component : c) {
			if (component instanceof javax.swing.JTextField) {
				JTextField jTextField = (JTextField) component;
				configProperties.setProperty(jTextField.getName(),jTextField.getText());
			}
		}
		writeProps2File(configProperties, configFilePath);
	}

	/**
	 * 
	 * 内部方法
	 * 
	 * <pre>
	 * 
	 * </pre>
	 * 
	 * @param configProperties
	 * @author jiajitao
	 * @param configFilePath
	 */
	private void writeProps2File(Properties configProperties,
			String configFilePath) {
		OutputStream fos = null;
		try {
			File file = new File(configFilePath);
			if (!file.getParentFile().exists()) {
				JOptionPane.showMessageDialog(setPanel, "参数配置文件不存在!", "错误：",
						JOptionPane.ERROR_MESSAGE);
				return;
			}
			fos = new FileOutputStream(file);
			configProperties.store(fos, "");
			JOptionPane.showMessageDialog(setPanel, "参数保存成功!", "提示：",
					JOptionPane.INFORMATION_MESSAGE);
		} catch (Exception e) {
			LogUtil.error("ftp参数保存错误", e);
			JOptionPane.showMessageDialog(setPanel, "保存参数配置出现错误!", "错误：",
					JOptionPane.ERROR_MESSAGE);
		} finally {
			CloseUtil.close(fos);
		}
	}

}
